import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import { setToken, getToken, getReToken, removeToken, removeReToken } from '@/utils/auth'
// 创建axios实例
const service = axios.create({
  /* baseURL: process.env.BASE_API, // api 的 base_url*/
  timeout: 5 * 1000, // 请求超时时间
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// request拦截器
service.interceptors.request.use(
  config => {
    // console.log(getToken()+":"+store.getters.token)
    if (getToken()) {
      config.headers['Authorization'] = getToken()
    } else {
      config.headers['Authorization'] = ''
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// 上传文件修改默认请求头
service.defaults.transformRequest = [function(data, config) {
  if (!config['Content-Type']) return JSON.stringify(data)
  switch (config['Content-Type'].toLowerCase()) {
    case 'application/json;charset=utf-8': {
      return JSON.stringify(data)
    }
    case 'multipart/form-data;charset=utf-8': {
      return data
    }
    default: {
      return JSON.stringify(data)
    }
  }
}]

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非0000抛错
     */
    const res = response.data
    if (res.code && res.code !== undefined && res.code !== '0000' && res.code !== '-1') {
      if (res.code === '1001') {
        Message({
          message: '加载异常',
          type: 'error',
          duration: 5 * 1000
        })
        return
      } else {
        Message({
          message: res.message || res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
